package fa7.socialcode.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import fa7.socialcode.dao.ComentarioDao;
import fa7.socialcode.model.Comentario;

@Repository(value = "comentarioDao")
public class ComentarioDaoHibernate implements ComentarioDao {

	HibernateTemplate hibernateTemplate;
	// Somente para log
	Log logger = LogFactory.getLog(ComentarioDaoHibernate.class);

	@Autowired
	public ComentarioDaoHibernate(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public Comentario findComentario(Long id) {
		Comentario comentario = (Comentario) hibernateTemplate.get(
				Comentario.class, id);
		if (comentario == null) {
			throw new ObjectRetrievalFailureException(Comentario.class, id);
		}
		return comentario;
	}

	public List findComentarios() {
		return hibernateTemplate.find("from Comentario");

	}

	public void removeComentario(Long id) {
		hibernateTemplate.delete(findComentario(id));

	}

	public void removeComentario(Comentario comentario) {
		hibernateTemplate.delete(findComentario(comentario.getId()));

	}

	public void saveComentario(Comentario comentario) {
		hibernateTemplate.saveOrUpdate(comentario);

		if (logger.isDebugEnabled()) {
			logger.debug("comentarioId set to: " + comentario.getId());
		}
	}

}
